
/**
 * 获取Request地址中的参数
 * @returns 
 */
function GetQueryParams() {
    var _url = location.search
    var _queryParams = new Object()
    if (_url.indexOf('?') != -1) {
        _url = _url.substring(1)
    }

    var params = _url.split('&')
    for (var i = 0; i < params.length; i++) {
        _queryParams[params[i].split('=')[0]] = params[i].split('=')[1]
    }
    return _queryParams
}

var Timer = new Object()
var QueryParams = new Object()
QueryParams = GetQueryParams()
var baseUrl = "https://crm.moguto.net"
var cityList = []

/**
 * 获取表单数据
 * 
 * @returns 
 */
function getFormData() {
    const loanAmount = $("#loanAmount").val()
    const name = $("#name").val()
    const sex = $("input[name='sex']:checked").val()
    const age = $("#age").val()
    const city = $("#city").val()
    const companyType = $('#companyType').val()
    const payTime = $('#payTime').val()
    const houseFund = $("#houseFund").val()
    const phoneNumber = $("#phoneNumber").val()
    const code = $("#code").val()
    const advertiserId = $("#advertiserId").text()
    const isAgreeProtocol = $("#isAgreeProtocol").is(':checked')

    return {
        loanAmount,
        name,
        sex,
        age,
        city,
        companyType,
        payTime,
        houseFund,
        phoneNumber,
        code,
        advertiserId,
        isAgreeProtocol
    }
}

/**
 * 验证表单信息
 * 
 * @returns 
 */
function validateForm() {
    const FormData = getFormData()

    if (!FormData.loanAmount) {
        Toast('请选择贷款金额')
        return false
    } else if (!FormData.city) {
        Toast('请选择城市')
        return false
    } else if (!FormData.companyType) {
        Toast('请选择工作单位类型')
        return false
    } else if (!FormData.payTime) {
        Toast('请选择公积金缴纳时长')
        return false
    } else if (!FormData.name) {
        Toast('请填写姓名')
        return false
    } else if (!(/^[\u4e00-\u9fa5]{1,4}$/.test(FormData.name))) {
        Toast('姓名请填写4字以内中文')
        return false
    } else if (!FormData.age) {
        Toast('请选择年龄')
        return false
    } else if (!(/^(\d){2}$/.test(FormData.age))) {
        Toast('年龄请填写2位数字')
        return false
    }

    return true
}

/**
 * 获取手机验证码
 */
function getVerifyCode() {
    var FormData = getFormData()
    var fetchParams = {
        "tenantId": QueryParams.tid,
        "phoneNum": FormData.phoneNumber
    }
    if(QueryParams.mgtId) {
        fetchParams.mgtId = QueryParams.mgtId
    }

    if (!FormData.phoneNumber) {
        Toast('请填写手机号')
        return
    } else if (!(/^1[3456789]\d{9}$/.test(FormData.phoneNumber))) {
        Toast('请填写正确手机号')
        return
    }

    $.ajax({
        type: 'GET',
        url: `${baseUrl}/api/dz-api/clue/send-verify-msg`,
        data: fetchParams,
        dataType: 'json',
        success: function(res) {
            Toast(res.code === 200 ? '短信发送成功' : res.msg);
            Log('「成功」验证短信验证码请求结果', res)

            var second = 60
            $('#sendVerifyCodeBtn').text(second + ' 秒')
            $('#sendVerifyCodeBtn').removeAttr("onclick")
            clearInterval(Timer)
            Timer = setInterval(() => {
                second--
                $('#sendVerifyCodeBtn').text(second + ' 秒')
                if (second <= 0) {
                    $('#sendVerifyCodeBtn').text('获取验证码')
                    $('#sendVerifyCodeBtn').attr("onclick","getVerifyCode()")
                    clearInterval(Timer)
                }
            }, 1000)
        },
        error: function() {
            Toast('短信发送失败');
            Log('「失败」验证短信验证码请求结果：异常')
            $('#sendVerifyCodeBtn').text('获取验证码')
            $('#sendVerifyCodeBtn').attr("onclick","getVerifyCode()")
            clearInterval(Timer)
        }
    })
}

/**
 * 验证手机验证码
 */
function checkVerifyCode(callback) {
    const FormData = getFormData()
    $.get(`${baseUrl}/api/dz-api/clue/check-verify-code`, {
        "code": FormData.code,
        "phoneNum": FormData.phoneNumber
    }, function (res) {
        Log('验证短信验证码请求结果', res)
        if (res.data.isSuccess) {
            callback(res.data.verifyCode)
        } else {
            Toast('请填写正确的验证码')
        }
    })
}
/**
 * 填写手机号验证码后跳转到第二页
 */
function toApplyPage() {
    // console.log(location);
    const FormData = getFormData()
    if (!FormData.phoneNumber) {
        Toast('请填写手机号')
        return false
    } else if (!(/^1[3456789]\d{9}$/.test(FormData.phoneNumber))) {
        Toast('请填写正确手机号')
        return false
    } else if (!FormData.code) {
        Toast('请填写验证码')
        return false
    } else if (!FormData.isAgreeProtocol) {
        Toast('请阅读并勾选协议')
        return false
    }
    checkVerifyCode(function (verifyCode) {
        sessionStorage.setItem('phoneNumber', FormData.phoneNumber)
        sessionStorage.setItem('verifyCode', verifyCode)
        $('#phone-page').hide()
        $('#apply-page').show()
    })
}

/**
 * 推送表单数据
 */
function pushFormData() {
    Log('开始推送线索数据')
    if (!validateForm()) {
        return
    }
    const FormData = getFormData()
    FormData.phoneNumber = sessionStorage.getItem('phoneNumber')
    FormData.verifyCode = sessionStorage.getItem('verifyCode')

    const tenantId = QueryParams.tid || ''
    const randomStr = Math.random().toFixed(6).slice(-6)
    const timestamp = new Date().getTime()
    const signature = md5(tenantId + FormData.phoneNumber + timestamp + randomStr);
    const clickId = QueryParams.clickid || QueryParams.gdt_vid || QueryParams.qz_gdt || QueryParams.bd_vid || ""

    const requestBody = {
        "tenantId": tenantId, //代投平台租户ID
        "advertiserId": FormData.advertiserId, //用户点击用户协议之后，会返回广告主对应的ID，再填充至该处
        "city": FormData.city, //用户点击用户协议之后，会返回广告主对应的城市，再填充至该处，
        "loanAmount": FormData.loanAmount,
        "name": FormData.name,
        "sex": FormData.sex,
        "age": FormData.age,
        "phoneNumber": FormData.phoneNumber,
        "verifyCode": FormData.verifyCode,
        "exdFields": {
            "promotionProduct": "3",
            "houseFund": '1',
            "companyType": FormData.companyType,
            "payTime": FormData.payTime,
        },

        accountCode: QueryParams.ac || "",
        channelCode: QueryParams.cc,
        cluePoolCode: QueryParams.cpc,
        pageCode: QueryParams.pc || "",
        productCode: QueryParams.prc || "",
        linkCode: QueryParams.lc || "",

        clickId: clickId,
        adId: QueryParams.adid || QueryParams.wx_aid || "",
        campaignId: QueryParams.campaignid || QueryParams.campaignId || "",
        creativeId: QueryParams.creativeid || QueryParams.creativeId || "",
        keywordId: QueryParams.keywordid || QueryParams.keywordId || "",
        projectId: QueryParams.projectid || QueryParams.projectId || "",
        promotionId: QueryParams.promotionid || QueryParams.promotionId || "",
        callbackId: clickId,
        callbackUrl: window.location.href,

        "randomStr": randomStr,
        "timestamp": timestamp,
        "signature": signature,
    }
    // 百度搜索url通配符,被替换为经过urlencode后的触发广告的关键字，urlencode前汉字编码为UTF-8，如关键字为鲜花，{kw_enc_utf8} 为 %E9%B2%9C%E8%8A%B1
    if(QueryParams.kwencutf8) {
        const keywordName = decodeURI(QueryParams.kwencutf8)
        requestBody.keywordName = keywordName
    }
    if(QueryParams.mgtId) {
        requestBody.mgtId = QueryParams.mgtId
    }
    Log('推送线索数据请求参数', requestBody)

    const loading = weui.loading('正在提交...')
    $.ajax({
        type: "POST",
        url: `${baseUrl}/api/dz-api/clue/access/ads`,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(requestBody),
        success: function (res) {
            loading.hide()
            Log('推送线索数据请求结果', res)
            location.href = 'resultv4.html?code=' + res.code || 200
        },
        error: function () {
            Log("推送线索数据请求失败")
            location.href = 'resultv4.html?code=500'
        }
    })
}

/**
 * 获取落地页当中配置的常用城市列表
 */
async function getCommonlyUsedCityList() {
    await getCommonCity().then(dataList => {
        if(dataList && dataList.length > 0) {
            let cityArr = []
            for(let i = 0; i<cityData.length; i++) {
                let province = cityData[i]
                if(dataList.length === cityArr.length) {
                    break
                }
                let children = []
                if(province.children && province.children.length > 0) {
                    province.children.forEach(item => {
                        dataList.forEach(d => {
                            if(item.label.indexOf(d) > -1 ) {
                                children.push(item)
                            }
                        })
                    })
                }
                if(children.length > 0) {
                    province.children = children
                    cityArr.push(province)
                }
            }
            cityList = cityArr
        } else {
            cityList = cityData
        }
    }).catch(() => {
        cityList = cityData
    })
    cityList.unshift({"value":-1,"label":"",children: [{ value: -999, label: ""}]})
}
function getCommonCity() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: `${baseUrl}/api/dz-api/wx-ad/city/list`,
            type: "get",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: { "pageCode": QueryParams.pc, "tenantId": QueryParams.tid },
            success: function (res) {
                resolve(res.data || [])
            },
            error: function(err) {
                reject(err)
            },
        })
    })
}

/**
 * 获取用户协议和隐私政策
 * 
 * @param {int} type 类型：1-用户协议、2-隐私政策 
 * @param {string} title 协议标题
 */
function getProtocol(type, title) {
    var text = ''
    if(type === 1) {
        text = protocolText
    } else if (type === 2) {
        text = privateText
    } else if (type === 3) {
        text = authorizeText
    } else if (type === 4) {
        text = riskText
    }
    $('#protocolTitle').text(title)
    $("#protocolContent").html('')
    $('.protocol_dialog_wrap').fadeIn(200)
    $('.protocol_dialog').addClass('weui-half-screen-dialog_show')

    $("#protocolContent").html(text)
    $(".page").css({
        "overflow-y": "hidden"
    })
}

/**
 * 关闭协议窗口
 */
function closeProtocolDialog() {
    $(".page").css({
        "overflow-y": "auto"
    })
    const $protocolDialogWrap = $('.protocol_dialog_wrap')
    $protocolDialogWrap.fadeOut(300)
    $protocolDialogWrap.find('.protocol_dialog').removeClass('weui-half-screen-dialog_show')
    setTimeout(function () {
        $protocolDialogWrap.trigger('focus')
    }, 300)
}

/**
 * 信息提示公共方法
 * 
 * @param {string} msgContent 提示内容
 * @returns 
 */
function Toast(msgContent) {
    var $textToast = $('#textToast')
    if ($textToast.css('display') != 'none') return

    $('.weui-toast__content').text(msgContent)

    $textToast.fadeIn(100);
    setTimeout(function () {
        $textToast.fadeOut(100)
    }, 1000);
}

/**
 * 打印日志
 * 
 * @param {string} title 标题
 * @param {string} content 内容
 */
function Log(title, content) {
    const isDebug = QueryParams.debug || false
    if (isDebug) {
        content ? console.log(title, content) : console.log(title)
    }
}

/**
 * 加入fx函数库
 */
;
(function ($, undefined) {
    var prefix = '',
        eventPrefix,
        vendors = {
            Webkit: 'webkit',
            Moz: '',
            O: 'o'
        },
        testEl = document.createElement('div'),
        supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
        transform,
        transitionProperty, transitionDuration, transitionTiming, transitionDelay,
        animationName, animationDuration, animationTiming, animationDelay,
        cssReset = {}

    function dasherize(str) {
        return str.replace(/([A-Z])/g, '-$1').toLowerCase()
    }

    function normalizeEvent(name) {
        return eventPrefix ? eventPrefix + name : name.toLowerCase()
    }

    if (testEl.style.transform === undefined) $.each(vendors, function (vendor, event) {
        if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
            prefix = '-' + vendor.toLowerCase() + '-'
            eventPrefix = event
            return false
        }
    })

    transform = prefix + 'transform'
    cssReset[transitionProperty = prefix + 'transition-property'] =
        cssReset[transitionDuration = prefix + 'transition-duration'] =
        cssReset[transitionDelay = prefix + 'transition-delay'] =
        cssReset[transitionTiming = prefix + 'transition-timing-function'] =
        cssReset[animationName = prefix + 'animation-name'] =
        cssReset[animationDuration = prefix + 'animation-duration'] =
        cssReset[animationDelay = prefix + 'animation-delay'] =
        cssReset[animationTiming = prefix + 'animation-timing-function'] = ''

    $.fx = {
        off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
        speeds: {
            _default: 400,
            fast: 200,
            slow: 600
        },
        cssPrefix: prefix,
        transitionEnd: normalizeEvent('TransitionEnd'),
        animationEnd: normalizeEvent('AnimationEnd')
    }

    $.fn.animate = function (properties, duration, ease, callback, delay) {
        if ($.isFunction(duration))
            callback = duration, ease = undefined, duration = undefined
        if ($.isFunction(ease))
            callback = ease, ease = undefined
        if ($.isPlainObject(duration))
            ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
        if (duration) duration = (typeof duration == 'number' ? duration :
            ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
        if (delay) delay = parseFloat(delay) / 1000
        return this.anim(properties, duration, ease, callback, delay)
    }

    $.fn.anim = function (properties, duration, ease, callback, delay) {
        var key, cssValues = {},
            cssProperties, transforms = '',
            that = this,
            wrappedCallback, endEvent = $.fx.transitionEnd,
            fired = false

        if (duration === undefined) duration = $.fx.speeds._default / 1000
        if (delay === undefined) delay = 0
        if ($.fx.off) duration = 0

        if (typeof properties == 'string') {
            // keyframe animation
            cssValues[animationName] = properties
            cssValues[animationDuration] = duration + 's'
            cssValues[animationDelay] = delay + 's'
            cssValues[animationTiming] = (ease || 'linear')
            endEvent = $.fx.animationEnd
        } else {
            cssProperties = []
            // CSS transitions
            for (key in properties)
                if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
            else cssValues[key] = properties[key], cssProperties.push(dasherize(key))

            if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
            if (duration > 0 && typeof properties === 'object') {
                cssValues[transitionProperty] = cssProperties.join(', ')
                cssValues[transitionDuration] = duration + 's'
                cssValues[transitionDelay] = delay + 's'
                cssValues[transitionTiming] = (ease || 'linear')
            }
        }

        wrappedCallback = function (event) {
            if (typeof event !== 'undefined') {
                if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
                $(event.target).unbind(endEvent, wrappedCallback)
            } else
                $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout

            fired = true
            $(this).css(cssReset)
            callback && callback.call(this)
        }
        if (duration > 0) {
            this.bind(endEvent, wrappedCallback)
            // transitionEnd is not always firing on older Android phones
            // so make sure it gets fired
            setTimeout(function () {
                if (fired) return
                wrappedCallback.call(that)
            }, ((duration + delay) * 1000) + 25)
        }

        // trigger page reflow so new elements can animate
        this.size() && this.get(0).clientLeft

        this.css(cssValues)

        if (duration <= 0) setTimeout(function () {
            that.each(function () {
                wrappedCallback.call(this)
            })
        }, 0)

        return this
    }

    testEl = null
})(Zepto)

/**
 * 扩展fadeIn、fadeOut函数
 */
;
(function ($) {
    $.extend($.fn, {
        fadeIn: function (speed, easing, complete) {
            if (typeof (speed) === 'undefined') speed = 400;
            if (typeof (easing) === 'undefined') {
                easing = 'swing';
            } else if (typeof (easing) === 'function') {
                if (typeof (complete) === 'undefined') complete = easing;
                easing = 'swing';
            }

            $(this).css({
                display: 'block',
                opacity: 0
            }).animate({
                opacity: 1
            }, speed, easing, function () {
                // complete callback
                complete && typeof (complete) === 'function' && complete();
            });

            return this;
        },
        fadeOut: function (speed, easing, complete) {
            if (typeof (speed) === 'undefined') speed = 400;
            if (typeof (easing) === 'undefined') {
                easing = 'swing';
            } else if (typeof (easing) === 'function') {
                if (typeof (complete) === 'undefined') complete = easing;
                easing = 'swing';
            }

            $(this).css({
                opacity: 1
            }).animate({
                opacity: 0
            }, speed, easing, function () {
                $(this).css('display', 'none');
                // complete callback
                complete && typeof (complete) === 'function' && complete();
            });

            return this;
        },
        fadeToggle: function (speed, easing, complete) {
            return this.each(function () {
                var el = $(this);
                el[(el.css('opacity') === 0 || el.css('display') === 'none') ? 'fadeIn' : 'fadeOut'](speed, easing, complete)
            })
        }
    })
})(Zepto);

$(function(){
    sessionStorage.removeItem('phoneNumber')
    sessionStorage.removeItem('verifyCode')
    $(document).bind("contextmenu",function(e){
        e.preventDefault();
        return false;
    });
    // 关闭协议弹窗
    $('.protocol_dialog_close').on('click', function() {
        closeProtocolDialog()
    })
    //隐私政策点击同意的逻辑
    $('.protocol_dialog_agree').on('click', function() {
        $("#isAgreeProtocol").prop("checked", true)
        closeProtocolDialog()
    })
    $('#showCityPicker').on('click', function(){
        $(".page").css({"overflow-y": "hidden"})
        $('#otherCityBtn').click()
    });

    $('#otherCityBtn').on('click', function () {
        $('#commonly_used_city').fadeOut(300)
        weui.picker(cityList, {
            id: 'cityPicker',
            title: '请选择工作城市',
            defaultValue: [-1,-999],
            depth: 2,
            onConfirm: function (result) {
                var cityLabel = result[0].label
                var cityValue = result[0].value
                if (result[0].label !== result[1].label) {
                    cityLabel = result[0].label + result[1].label
                }
                if(cityValue === -1) {
                    $('#city').val('')
                    $('#city-label').html('请选择工作城市')
                    $('#city-label').css("color", 'rgba(0, 0, 0, 0.3)')
                } else {
                    $('#city').val(result[1].label)
                    $('#city-label').html(cityLabel)
                    $('#city-label').css("color", "#000")
                }
            },
            onClose: function () {
                $(".page").css({"overflow-y": "auto"})
            },
        })
    })

    $('.commonly_used_city_close').on('click', function () {
        $(".page").css({"overflow-y": "auto"})
        $('#commonly_used_city').fadeOut(300)
    })

    $('#showCompanyTypePicker').on('click', function () {
        $(".page").css({"overflow-y": "hidden"})
        weui.picker([{
            label: '国企单位', 
            value: '国企单位'
        }, {
            label: '公职单位', 
            value: '公职单位'
        }, {
            label: '民营单位', 
            value: '民营单位'
        }, {
            label: '外资单位', 
            value: '外资单位'
        }, {
            label: '自由职业', 
            value: '自由职业'
        }], {
            id: 'showCompanyTypePicker',
            title: '请选择工作单位类型',
            defaultValue: ['国企单位'],
            onConfirm: function (result) {
                $('#company-type-label').html(result[0].label)
                $('#company-type-label').css("color", "#000")
                $('#companyType').val(result[0].value);
            },
            onClose: function () {
                $(".page").css({"overflow-y": "auto"})
            },
        })
    })

    $('#showPayTimePicker').on('click', function () {
        $(".page").css({"overflow-y": "hidden"})
        weui.picker([{
            label: '没有交或当前停交', 
            value: '没有交或当前停交'
        }, {
            label: '0-6个月', 
            value: '0-6个月'
        }, {
            label: '6-12个月', 
            value: '6-12个月'
        }, {
            label: '12个月以上', 
            value: '12个月以上'
        }], {
            id: 'showPayTimePicker',
            title: '请选择公积金缴纳时长',
            defaultValue: ['6-12个月'],
            onConfirm: function (result) {
                $('#pay-time-label').html(result[0].label)
                $('#pay-time-label').css("color", "#000")
                $('#payTime').val(result[0].value);
            },
            onClose: function () {
                $(".page").css({"overflow-y": "auto"})
            },
        })
    })

    $('#showLoanAmountPicker').on('click', function () {
        $(".page").css({"overflow-y": "hidden"})
        weui.picker([{
                label: '5万', 
                value: 5
            }, {
                label: '10万', 
                value: 10
            }, {
                label: '20万', 
                value: 20
            }, {
                label: '30万', 
                value: 30
            }, {
                label: '50万', 
                value: 50
            }, {
                label: '80万', 
                value: 80
            }, {
                label: '100万', 
                value: 100
            }, {
                label: '200万', 
                value: 200
            }], {
            id: 'loanAmountPicker',
            title: '请选择贷款金额',
            defaultValue: [20],
            onConfirm: function (result) {
                $('#loanAmount-label').html(result[0].label)
                $('#loanAmount-label').css("color", "#000")
                $('#loanAmount').val(result[0].value)
            },
            onClose: function () {
                $(".page").css({"overflow-y": "auto"})
            },
        })
    })
    $('#showAgePicker').on('click', function () {
        $(".page").css({"overflow-y": "hidden"})
        let ageArr = []
        for(let i = 24; i < 51; i++) {
            ageArr.push({
                label: i + '岁',
                value: i
            })
        }
        weui.picker(ageArr, {
            id: 'showAgePicker',
            title: '请选择年龄',
            defaultValue: [30],
            onConfirm: function (result) {
                $('#age-label').html(result[0].label)
                $('#age-label').css("color", "#000")
                $('#age').val(result[0].value)
            },
            onClose: function () {
                $(".page").css({"overflow-y": "auto"})
            },
        })
    })

    getCommonlyUsedCityList()
});